/**
 * 全局状态
 */
var store = {
    debug: false,
    state: {
        loginDialog: false,
    },
    setLoginDialog (newValue) {
        this.state.loginDialog = newValue
    },
}

/**
 * 网络请求(全局使用此方法进行请求接口)
 */
var request = {
	/**
	 * 发送post请求
	 * @param  {String} url   链接
	 * @param  {Object} data  数据集
	 */
	post(url, data, callback = ""){
		$.ajax({
			url: index_url(url),
			type: 'post',
			dataTyle: 'json',
			data: data,
			success:function(res) {
				var res = typeof res == 'string' ? JSON.parse(res) : res;
				if (res.status === 'login') {
					store.setLoginDialog(true); // 打开登录弹窗
					if (callback != "") callback(res);
				} else {
					if (callback != "") callback(res);
				}
			},
			error:function(res) {
				res.status  = 'error';
				res.message = res.statusText;
				if (callback != "") callback(res);
			}
		})
	},
}
/**
 * 分享网站
 */
var share = function(name)
{
    var list =
    {
        //微信
        'wechat': function(selector){$(selector).append('<img src="http://qr.liantu.com/api.php?text='+encodeURIComponent(window.location.href)+'" />').show()},
        //新浪微博
        'sina'     : 'http://service.weibo.com/share/share.php?title=__shareTitle__&url=__shareUrl__&language=zh_cn',
        //脸书
        'facebook' : 'http://www.facebook.com/sharer.php?u=__shareUrl__&t=__shareTitle__',
        //推特
        'twitter'  : 'http://twitter.com/?status=__shareUrl__%20-%20__shareTitle__',
        //pin
        'pinterest': 'http://pinterest.com/pin/create/button/?url=__shareUrl__&media=__shareTitle__',
        // linkedin
        'linkedin' : 'http://www.linkedin.com/shareArticle?url=__shareUrl__',
    };
    if(typeof(list[name]) == 'undefined') {
        alert('暂未开放');
        return;
    } else if(typeof(list[name]) == 'function') {
        list[name](arguments[1]);
    } else if(typeof(list[name]) == 'string') {
        var url = list[name].replace('__shareUrl__',encodeURIComponent(window.location.href)).replace('__shareTitle__',encodeURIComponent(document.title));
        window.open(url,"Both","width=850,height=520,menubar=0,scrollbars=1,resizable=1,status=1,titlebar=0,toolbar=0,location=1");
    }
};
/**
 * 链接
 */
var locationUrl = {
	/**
	 * 获取链接参数
	 * @param  {String} name 参数名
	 */
	get(name) {
	    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
	    var u = decodeURI(window.location.search.substr(1));
	    var r = u.match(reg); 
	    if (r != null) return unescape(r[2]); 
	    return "";
	},
	/**
	 * 设置链接参数
	 * @param  {String} name  参数名
	 * @param  {String} value 值
	 */
	set(name, value){
		var loadUrl = location.href;
		var arrUrl  = loadUrl.split('#');
		var url     = arrUrl[0];
		var pattern = name + '=([^&]*)';
	    var replaceText = name+'='+value; 
	    var newUrl = "";
	    if (url.match(pattern)) {
	        var tmp = '/(' + name + '=)([^&]*)/gi';
	        newUrl = url.replace(eval(tmp),replaceText);
	    } else { 
	        if (url.match('[\?]')) { 
	            newUrl = url + '&' + replaceText; 
	        } else {
	            newUrl =  url +'?' + replaceText; 
	        } 
	    }
	    location.href = newUrl+window.location.hash
	}
}
/**
 * 树形数组
 */
var tree = {
	/**
	 * 根据字符串查找当前所在节点
	 * @param  {Array} tree      数组
	 * @param  {String} value    配置的值
	 * @param  {String} field    匹配的字段
	 * @param  {String} children 匹配的字段子类
	 * @param  {Number} level    等级
	 * @return {Object}          当前节点
	 */
	getNode(tree, value, field = "id", children = "children", level = 0){
		if (tree[field] == value) {
	        return tree;
	    } else {
	        if (level > 0) {
	            tree = tree[children] ? tree[children] : [];
	        }
	        for (let i = 0, n = tree.length; i < n; i++) {
	            let node = this.getNode(tree[i], value, field, children, 1)
	            if (node) {
	                return node;
	            }
	        }
	    }
	},
	/**
	 * 数组转树形
	 * @param  {Array} data 需转换的数组
	 * @return {Array}      树形数组  
	 */
	convert(data) {
	    let result = []
	    if (!Array.isArray(data)) {
	        return result
	    }
	    data.forEach(item => {
	        delete item.children;
	    });
	    let map = {};
	    data.forEach(item => {
	        map[item.id] = item;
	    });
	    data.forEach(item => {
	        let parent = map[item.pid];
	        if(parent) {
	            (parent.children || (parent.children = [])).push(item);
	        } else {
	            result.push(item);
	        }
	    });
	    result = result.filter(ele => ele.pid == 0);
	    return result;
	},
	/**
	 * 数组转树形字符串数组
	 * @param  {Array} arr     需转换的数组
	 * @param  {Number} pid    pid值
	 * @param  {String} format 字符串的标识
	 * @param  {Array}  list   遍历数组
	 * @return {Array}         数组
	 */
	convertString(arr, pid = 0, format = "<span class='mk-tree-string'>└</span>", list = []) {
		arr.forEach(function(v, k){
			if (v['pid'] == pid) {
				if (pid != 0) {
					v['treeString'] = format;
				}
				list.push(v)
				tree.convertString(arr, v['id'], "<span class='mk-tree-interval'></span>"+format, list);
			}
		});
		return list;
	},
	/**
	 * 树形数组转二维数组
	 * @param  {Array} data 需转换的数组
	 * @return {Array}      数组
	 */
	revert(data) {
		for (var i = 0; i < data.length; i++) {
			if (data[i].children != undefined) {
				var temp = data[i].children;
				// 删除孩子节点
				delete data[i].children;
				// 孩子节点加入数组末尾
				for (var j = 0; j < temp.length; j++) {
					data.push(temp[j]);
				}
			}
		}
		return data;
	},
}
/**
 * localStorage缓存
 */
var storage = {
	/**
	 * 设置缓存
	 * @param {String} key    缓存名称
	 * @param {[type]} value  缓存值
	 * @param {[type]} expire 缓存时长(毫秒)
	 */
	set(key, value, expire){
	    let obj = {
	        data: value,
	        time: Date.now(),
	        expire: expire
	    };
	    localStorage.setItem(key, JSON.stringify(obj));
	},
	/**
	 * 获取缓存
	 * @param  {String} key 缓存名称
	 */
	get(key){
	    let val = JSON.parse(localStorage.getItem(key));
	    if (!val) {
	        return val;
	    }
	    if (Date.now() - val.time > val.expire) {
	        localStorage.removeItem(key);
	        return null;
	    }
	    return val.data;
	}
}

/**
 * 公共函数
 */
var common = {
	/**
	 * 返回随机默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
	 */
	id(len = 36) {
		var chars  = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
		var maxPos = chars.length;
		var id = '';
		for (i = 0; i < len; i++) {
			id += chars.charAt(Math.floor(Math.random() * maxPos));
		}
		return id;
	},
	/**
	 * 日期时间格式
	 * @return {String} Y-m-d H:i:s
	 */
	dateTime(para = '') {
		let date = para === '' ? new Date() : para;
		let year = date.getFullYear(); // 年
		let month = date.getMonth() + 1; // 月
		let day = date.getDate(); // 日
		let hour = date.getHours(); // 时
		hour = hour < 10 ? "0" + hour : hour; // 如果只有一位，则前面补零
		let minute = date.getMinutes(); // 分
		minute = minute < 10 ? "0" + minute : minute; // 如果只有一位，则前面补零
		let second = date.getSeconds(); // 秒
		second = second < 10 ? "0" + second : second; // 如果只有一位，则前面补零
		return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
	},
	/**
	 * 获取数组某匹配值的下标
	 * @param  {Array} arr    数组
	 * @param  {String} value 匹配值
	 * @param  {String} field 匹配字段
	 * @return {Number}       下标
	 */
	arrayIndex(arr, value, field = "id"){
	    let index = -1;
	    arr.forEach(function(val, key) {
	        if (val[field] == value) {
	            index = key;
	        }
	    });
	    return index;
	},
}

/**
 * 文件处理
 */
var file = {
	/**
	 * 获取文件大小
	 * @param  {Number} Bytes 字节
	 */
	getSize(Bytes) {
	    if (null == Bytes || Bytes == '') {
	        return "0 Bytes";
	    }
	    var unitArr = new Array("Bytes","KB","MB","GB","TB","PB","EB","ZB","YB");
	    var index = 0,
	    srcsize = parseFloat(Bytes);
		index = Math.floor(Math.log(srcsize) / Math.log(1024));
	    var size = srcsize / Math.pow(1024,index);
	    size = size.toFixed(2);
	    return size+unitArr[index];
	},
	/**
	 * 文件类型、名称
	 * @param  {String} url 文件链接
	 * @return {Object}     文件类型、名称
	 */
	getType(url) {
		let arr    = url.split('.');
		let suffix = arr[arr.length-1];
		var value  = {};
		switch(suffix){
			case ('png'):
			case ('jpg'):
			case ('jpeg'):
			case ('bmp'):
			case ('gif'):
			case ('ico'):
				value['name'] = "图片";
				value['type'] = "image";
				break;
			case ('mp4'):
			case ('m2v'):
			case ('mkv'):
			case ('wmv'):
				value['name'] = "视频";
				value['type'] = "video";
				break;
			case ('mp3'):
			case ('wav'):
				value['name'] = "音频";
				value['type'] = "audio";
				break;
			case ('txt'):
				value['name'] = "文本";
				value['type'] = "txt";
				break;
			case ('xls'):
			case ('xlsx'):
				value['name'] = "Excel文件";
				value['type'] = "xls";
				break;
			case ('doc'):
			case ('docx'):
				value['name'] = "Word文件"
				value['type'] = "word";
				break;
			case ('pdf'):
				value['name'] = "PDF文件"
				value['type'] = "pdf";
				break;
			case ('ppt'):
				value['name'] = "PPT文件"
				value['type'] = "ppt";
				break;
			case ('rar'):
			case ('zip'):
				value['name'] = "压缩文件";
				value['type'] = "zip";
				break;
			case ('dll'):
				value['name'] = "动态链接库";
				value['type'] = "dll";
				break;
			case ('torrent'):
				value['name'] = "BT文件";
				value['type'] = "torrent";
				break;
			case ('dwt'):
				value['name'] = "Dreamweaver文件";
				value['type'] = "dwt";
				break;
			case ('psd'):
				value['name'] = "Photoshop文件";
				value['type'] = "psd";
				break;
			case ('swf'):
				value['name'] = "Flash文件";
				value['type'] = "swf";
				break;
			default:
				value['name'] = "未知文件"
				value['type'] = "other";
				break;
		}
		return value;
	}
}

/**
 * 获取语言
 */
function lang(name) {
    return typeof langPara[name] === "undefined" || langPara[name] === "" ? name : langPara[name];
}

/**
 * 获取url
 */
function index_url(url) {
    return splitUrl.replace('decoration/your-link', url);
}